/*
 * @(#)DmsEmailAuditTrailManager.java
 *
 * Copyright (c) 2005 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.core;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.impl.LogFactoryImpl;

import uk.ltd.getahead.dwr.ExecutionContext;

import com.dcivision.dms.bean.DmsEmailAuditTrail;
import com.dcivision.dms.dao.DmsEmailAuditTrailDAObject;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.UserInfoFactory;
import com.dcivision.framework.Utility;

/**
 * <p>Class Name:       DmsEmailAuditTrailManager.java    </p>
 * <p>Description:      The class mainly handle the email Audit Trail  .</p>
 * @author              barbin
 * @company             DCIVision Limited
 * @creation date       13/09/2006
 * @version             $Revision: 1.3.2.1 $
 */

public class DmsEmailAuditTrailManager {
  protected Log log = new LogFactoryImpl().getInstance(this.getClass());  
  private SessionContainer sessionContainer;
  private Connection conn;
  private HttpServletRequest request;
  private static String FLAG="|";

  
	/**
   *  Constructor - Creates a new instance of DocumentEmailArchiveManager
   */
  public DmsEmailAuditTrailManager() {
    super();
  }
  
  /*******************
   * 
   * @param sessionContainer
   * @param conn
   */
  public DmsEmailAuditTrailManager(SessionContainer sessionContainer, Connection conn) {
    this.sessionContainer = sessionContainer;
    this.conn = conn;
  }
  
	/**
   *  Release - release all variable in instance of DocumentEmailArchiveManager
   */
  public synchronized void release() {
    this.sessionContainer = null;
    this.conn = null;
  }
  
 /************************
  * 1. parse the arguments.
  * 2. convert to array
  * 3. put the per array value set to emailAuditTrail
  * 4. get the result list with emailAuditTrail.
  * 5. convert the result list generate a new Arraylist and pass to page
  * Main function: this method get the auguments from page .then parse it set to DmsEmailAuditTrail bean.
  * get list result generate the like array list return to page by dwr library.
  * @param arguments
  * @return List result
  */
  public List getList(String arguments){
  	List result = new ArrayList();
  	List pageList = new ArrayList();
  	DmsEmailAuditTrail emailAuditTrail = new DmsEmailAuditTrail();
  	// parse arguments from page transation . and set value toemailAuditTrail
  	//1.
  	String[] args = TextUtility.splitString(arguments,"|");
  	//2.
  	emailAuditTrail.setOperation(args[0]);
  	emailAuditTrail.setOperationSearchType(args[1]);
  	emailAuditTrail.setUserid(TextUtility.parseIntegerObj(args[2]));
  	emailAuditTrail.setUserSearchType(args[3]);
  	emailAuditTrail.setEmailFrom(args[4]);
  	emailAuditTrail.setFromSearchType(args[5]);
  	emailAuditTrail.setEmailTo(args[6]);
  	emailAuditTrail.setToSearchType(args[7]);
  	emailAuditTrail.setEmailCc(args[8]);
  	emailAuditTrail.setCcSearchType(args[9]);
  	emailAuditTrail.setEmailBcc(args[10]);
  	emailAuditTrail.setBccSearchType(args[11]);
  	emailAuditTrail.setEmailSubject(args[12]);
  	emailAuditTrail.setSubjectSearchType(args[13]);
  	emailAuditTrail.setAttchName(args[14]);
  	emailAuditTrail.setAttchNameSearchType(args[15]);
  	emailAuditTrail.setEmailType(args[16]);
  	emailAuditTrail.setTypeSearchType(args[17]);
  	emailAuditTrail.setSentDate(args[18]);
  	emailAuditTrail.setSentDateSearchType(args[19]);
  	emailAuditTrail.setSentDateValue(args[20]);
  	emailAuditTrail.setSecondDate(args[21]);
  	emailAuditTrail.setSecondDateSearchType(args[22]);
  	emailAuditTrail.setSecondDateValue(args[23]);
  	emailAuditTrail.setSortAttribute(args[24]);
  	emailAuditTrail.setSortOrder(args[25]);
  	emailAuditTrail.setCurStartRowNo(args[26]);
  	try{
  		// 3.get result list
  		result = getSearchList(emailAuditTrail);
  		
  		// 4.convert the list to String generate a new List pass to page
  		for(int i=0; i<result.size(); i++){
  			StringBuffer sb = new StringBuffer();
  			DmsEmailAuditTrail dmsEmailAuditTrail = (DmsEmailAuditTrail)result.get(i);
  			sb.append(dmsEmailAuditTrail.getRecordCount()).append(FLAG)//0
  			.append(dmsEmailAuditTrail.getRowNum()).append(FLAG)//1
  			.append(dmsEmailAuditTrail.getID().toString()).append(FLAG)//2
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getEmailType())?"null":dmsEmailAuditTrail.getEmailType()).append(FLAG)//3
  			.append(UserInfoFactory.getUserFullName(dmsEmailAuditTrail.getUserid())).append(FLAG)//4
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getOperation())?"null":dmsEmailAuditTrail.getOperation()).append(FLAG)//5
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getEmailFrom())?"null":dmsEmailAuditTrail.getEmailFrom()).append(FLAG)//6
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getEmailTo())?"null":dmsEmailAuditTrail.getEmailTo()).append(FLAG)//7
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getEmailCc())?"null":dmsEmailAuditTrail.getEmailCc()).append(FLAG)//8
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getEmailBcc())?"null":dmsEmailAuditTrail.getEmailBcc()).append(FLAG)//9
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getEmailSubject())?"null":dmsEmailAuditTrail.getEmailSubject()).append(FLAG)//10
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getSentDate())?"null":dmsEmailAuditTrail.getSentDate().toString()).append(FLAG)//11
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getAttchName())?"null":dmsEmailAuditTrail.getAttchName()).append(FLAG)//12
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getAttchCount())?"null":dmsEmailAuditTrail.getAttchCount().toString()).append(FLAG)//13
  			.append(Utility.isEmpty(dmsEmailAuditTrail.getAttchSource())?"null":dmsEmailAuditTrail.getAttchSource()).append(FLAG)
  			.append(Utility.isEmpty(args[24])?"null":args[24]).append(FLAG)
  			.append(Utility.isEmpty(args[25])?"null":args[25]);//14
  			pageList.add(sb.toString());
  		}
  	}catch(Exception e){
      log.error(e, e);
  	}
  	
  	//if the page list is null. the add this record
  	if(pageList.size()==0){
  		pageList.add("0|0|0|null|null|null|null|null|null|null|null|null|null|null|null");
  	}
  	return pageList;
  }
  
  
  /***************
   * 1. judagement the emailAuditTrail arguments . 
   * 2. convert the sent date if sent date not a spectify value
   * 3. parse and convert the second date
   * 4. get result for generate pdf file list
   * the main function: this method reponseability get the search condition all result generate the pdf document
   * @param emailAuditTrail
   * @return
   * @throws ApplicationException
   */
  
  public List getPDFDefaultList(DmsEmailAuditTrail emailAuditTrail) throws ApplicationException{
  	DmsEmailAuditTrailDAObject dmsEmailAuditTrailDAO = new DmsEmailAuditTrailDAObject(sessionContainer, conn);
  	List result = new ArrayList();
  	try{
  		
  		// justly the date search condition
  		//1.
  		if(!Utility.isEmpty(emailAuditTrail.getSentDateValue())&&!emailAuditTrail.getSentDateValue().equals("specificDate")){
  			String date1 = emailAuditTrail.getSentDateValue();
      	Calendar cal = Calendar.getInstance();
      	Calendar secondCal = Calendar.getInstance();
      	if(date1.equals("today")){
      		
      	}else if(date1.equals("yesterday")){
			cal.add(Calendar.DATE,-1);
			secondCal.add(Calendar.DATE,-1);
		}else if(date1.equals("thisWeek")){
			cal.add(Calendar.DATE,1-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,7-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastWeek")){
			cal.add(Calendar.DATE,1-7-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,1-1-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("2WeekBefore")){
			cal.add(Calendar.DATE,1-14-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("3WeekBefore")){
			cal.add(Calendar.DATE,1-21-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastMonth")){
			cal.add(Calendar.MONTH,-1);
			cal.set(Calendar.DATE,1);
			secondCal.set(Calendar.DATE,0);
			
		}else if(date1.equals("2MonthBefore")){
			cal.add(Calendar.MONTH,-2);
		}
      	cal.set(Calendar.AM_PM, Calendar.AM);
        cal.set(Calendar.HOUR, 0);   
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        String fromDateValue = TextUtility.formatDate(cal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
       
        secondCal.set(Calendar.AM_PM, Calendar.PM);
        secondCal.set(Calendar.HOUR, 11);
        secondCal.set(Calendar.MINUTE, 59);
        secondCal.set(Calendar.SECOND, 59);
        secondCal.set(Calendar.MILLISECOND, 59);
        String toDateValue = TextUtility.formatDate(secondCal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
        emailAuditTrail.setFromTime(fromDateValue);
  			emailAuditTrail.setToTime(toDateValue);
        if(date1.equals("2WeekBefore") || date1.equals("3WeekBefore") || date1.equals("2MonthBefore")){
        	emailAuditTrail.setToTime("");
        }
  		}else{
  			emailAuditTrail.setFromTime("");
  			emailAuditTrail.setToTime("");
  		}
  		//2.
  		if(!Utility.isEmpty(emailAuditTrail.getSecondDateValue())&&!emailAuditTrail.getSentDateValue().equals("specificDate")){
  			String date1 = emailAuditTrail.getSecondDateValue();
      	Calendar cal = Calendar.getInstance();
      	Calendar secondCal = Calendar.getInstance();
      	if(date1.equals("today")){
      		
      	}else if(date1.equals("yesterday")){
			cal.add(Calendar.DATE,-1);
			secondCal.add(Calendar.DATE,-1);
		}else if(date1.equals("thisWeek")){
			cal.add(Calendar.DATE,1-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,7-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastWeek")){
			cal.add(Calendar.DATE,1-7-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,1-1-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("2WeekBefore")){
			cal.add(Calendar.DATE,1-14-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("3WeekBefore")){
			cal.add(Calendar.DATE,1-21-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastMonth")){
			cal.add(Calendar.MONTH,-1);
			cal.set(Calendar.DATE,1);
			secondCal.set(Calendar.DATE,0);
			
		}else if(date1.equals("2MonthBefore")){
			cal.add(Calendar.MONTH,-2);
		}
      	cal.set(Calendar.AM_PM, Calendar.AM);
        cal.set(Calendar.HOUR, 0);   
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        String fromDateValue = TextUtility.formatDate(cal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
       
        secondCal.set(Calendar.AM_PM, Calendar.PM);
        secondCal.set(Calendar.HOUR, 11);
        secondCal.set(Calendar.MINUTE, 59);
        secondCal.set(Calendar.SECOND, 59);
        secondCal.set(Calendar.MILLISECOND, 59);
        String toDateValue = TextUtility.formatDate(secondCal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
        emailAuditTrail.setSecFromTime(fromDateValue);
  			emailAuditTrail.setSecToTime(toDateValue);
        if(date1.equals("2WeekBefore") || date1.equals("3WeekBefore") || date1.equals("2MonthBefore")){
        	emailAuditTrail.setSecToTime("");
        }
  		}else{
  			emailAuditTrail.setSecFromTime("");
  			emailAuditTrail.setSecToTime("");
  		}
  		//3.
  		result = dmsEmailAuditTrailDAO.getPDFDefaultList(emailAuditTrail);	
  	}catch(Exception e){
      log.error(e, e);
  	}
  	return result;
  }
  
  /*****************
   * 1. judagement the emailAuditTrail arguments . 
   * 2. convert the sent date if sent date not a spectify value
   * 3. parse and convert the second date
   * 4. get result for generate pdf file list
   * @param emailAuditTrail
   * @return
   * @throws ApplicationException
   */
  public List getSearchList(DmsEmailAuditTrail emailAuditTrail)throws ApplicationException{
  	request = ExecutionContext.get().getHttpServletRequest();
  	sessionContainer = getSessionContainer(request);
  	conn = getDBConnection();
    DmsEmailAuditTrailDAObject dmsEmailAuditTrailDAO = new DmsEmailAuditTrailDAObject(sessionContainer, conn);
  	List result = new ArrayList();
  	try{
  		//1.
  		if(!Utility.isEmpty(emailAuditTrail.getSentDateValue())&&!emailAuditTrail.getSentDateValue().equals("specificDate")){
  			String date1 = emailAuditTrail.getSentDateValue();
      	Calendar cal = Calendar.getInstance();
      	Calendar secondCal = Calendar.getInstance();
      	if(date1.equals("today")){
      		
		}else if(date1.equals("yesterday")){
			cal.add(Calendar.DATE,-1);
			secondCal.add(Calendar.DATE,-1);
		}else if(date1.equals("thisWeek")){
			cal.add(Calendar.DATE,1-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,7-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastWeek")){
			cal.add(Calendar.DATE,1-7-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,1-1-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("2WeekBefore")){
			cal.add(Calendar.DATE,1-14-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("3WeekBefore")){
			cal.add(Calendar.DATE,1-21-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastMonth")){
			cal.add(Calendar.MONTH,-1);
			cal.set(Calendar.DATE,1);
			secondCal.set(Calendar.DATE,0);
			
		}else if(date1.equals("2MonthBefore")){
			cal.add(Calendar.MONTH,-2);
		}
      	cal.set(Calendar.AM_PM, Calendar.AM);
        cal.set(Calendar.HOUR, 0);   
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        String fromDateValue = TextUtility.formatDate(cal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
       
        secondCal.set(Calendar.AM_PM, Calendar.PM);
        secondCal.set(Calendar.HOUR, 11);
        secondCal.set(Calendar.MINUTE, 59);
        secondCal.set(Calendar.SECOND, 59);
        secondCal.set(Calendar.MILLISECOND, 59);
        String toDateValue = TextUtility.formatDate(secondCal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
        emailAuditTrail.setFromTime(fromDateValue);
  			emailAuditTrail.setToTime(toDateValue);
        if(date1.equals("2WeekBefore") || date1.equals("3WeekBefore") || date1.equals("2MonthBefore")){
        	emailAuditTrail.setToTime("");
        }
  		}else{
  			emailAuditTrail.setFromTime("");
  			emailAuditTrail.setToTime("");
  		}
  		//2.
  		if(!Utility.isEmpty(emailAuditTrail.getSecondDateValue())&&!emailAuditTrail.getSentDateValue().equals("specificDate")){
  			String date1 = emailAuditTrail.getSecondDateValue();
      	Calendar cal = Calendar.getInstance();
      	Calendar secondCal = Calendar.getInstance();
      	if(date1.equals("today")){
      		
      	}else if(date1.equals("yesterday")){
			cal.add(Calendar.DATE,-1);
			secondCal.add(Calendar.DATE,-1);
		}else if(date1.equals("thisWeek")){
			cal.add(Calendar.DATE,1-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,7-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastWeek")){
			cal.add(Calendar.DATE,1-7-cal.get(Calendar.DAY_OF_WEEK));
			secondCal.add(Calendar.DATE,1-1-secondCal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("2WeekBefore")){
			cal.add(Calendar.DATE,1-14-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("3WeekBefore")){
			cal.add(Calendar.DATE,1-21-cal.get(Calendar.DAY_OF_WEEK));
		}else if(date1.equals("lastMonth")){
			cal.add(Calendar.MONTH,-1);
			cal.set(Calendar.DATE,1);
			secondCal.set(Calendar.DATE,0);
			
		}else if(date1.equals("2MonthBefore")){
			cal.add(Calendar.MONTH,-2);
		}
      	cal.set(Calendar.AM_PM, Calendar.AM);
        cal.set(Calendar.HOUR, 0);   
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        String fromDateValue = TextUtility.formatDate(cal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
       
        secondCal.set(Calendar.AM_PM, Calendar.PM);
        secondCal.set(Calendar.HOUR, 11);
        secondCal.set(Calendar.MINUTE, 59);
        secondCal.set(Calendar.SECOND, 59);
        secondCal.set(Calendar.MILLISECOND, 59);
        String toDateValue = TextUtility.formatDate(secondCal.getTime(), SystemParameterFactory.getSystemParameter(SystemParameterConstant.DB_DATETIME_FORMAT));
        emailAuditTrail.setSecFromTime(fromDateValue);
  			emailAuditTrail.setSecToTime(toDateValue);
        if(date1.equals("2WeekBefore") || date1.equals("3WeekBefore") || date1.equals("2MonthBefore")){
        	emailAuditTrail.setSecToTime("");
        }
  		}else{
  			emailAuditTrail.setSecFromTime("");
  			emailAuditTrail.setSecToTime("");
  		}
  		//3.
  		result = dmsEmailAuditTrailDAO.getSearchList(emailAuditTrail);
  	}catch(Exception e){
      log.error(e, e);
  	}
  	conn = null;
  	return result;
  }
  
  
  /**********************
   * get sessionContainer
   * @param request
   * @return
   */
  private SessionContainer getSessionContainer(HttpServletRequest request) {
    SessionContainer ctx = (SessionContainer)request.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    if (ctx==null) {
      ctx = new SessionContainer();
      request.getSession().setAttribute(GlobalConstant.SESSION_CONTAINER_KEY, ctx);
    }
    return(ctx);
  }
  

  /*********************
   * get Database connection
   * @return
   */
  private Connection getDBConnection(){
  	if(this.conn!=null){
  		return conn;
  	}else{
  		try{
  			conn=DataSourceFactory.getConnection();
  		}catch(Exception e){
  			log.error("get Connection error!");
  		}
  		return conn;
  	}
  }
  
}
